<template>
    <section>
        <!--工具条-->

        <div class="section-content clearfix">
            <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="filters">
                    <!-- <el-form-item style="float: left;">
                        <el-input v-model="filters.name" placeholder="角色名" @keyup.enter.native="getUsers()"></el-input>
                    </el-form-item>
                    <el-form-item class="tool-bt">
                        <el-button :type="buttonColor" v-on:click="getUsers">查询</el-button>
                    </el-form-item> -->
                    <el-form-item v-if="menubt.indexOf('/role/post')>-1">
                        <el-button :type="buttonColor" @click="handleAdd">新增</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <!--列表-->
            <el-table :data="users" highlight-current-row v-loading="listLoading" :header-row-style="{backgroundColor: titleColor}" @selection-change="selsChange" style="width: 100%;">
          
                <el-table-column align="center" type="index" label="序号" :index="indexMethod" width="80">
                </el-table-column>
                <el-table-column align="center" prop="name" label="角色名">
                </el-table-column>
                <el-table-column align="center" prop="createTime" label="时间">
                </el-table-column>
                <!-- <el-table-column    label="优先级">
                </el-table-column> -->

                <el-table-column align="center" prop="remark"  label="描述">
                </el-table-column>
                <el-table-column align="center" v-if="menubt.indexOf('/role/get')>-1" label="权限树">
                    <template scope="scope">
                        <el-button v-if="scope.row.id!=10" size="small" @click="exentEdit(scope.$index, scope.row)" icon="el-icon-bell" circle
                            title="权限树"></el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="150">
                    <template scope="scope">
                        
                        <!-- <i v-if="menubt.indexOf('/role/put')>-1" @click="handleEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>
                        <i v-if="menubt.indexOf('/role/delete')>-1&&scope.row.id!=10" @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除" class="pb-icon icon-delete"></i> -->
                        <i v-if="scope.row.userId===selfId" @click="handleEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>
                        <i v-if="scope.row.userId===selfId" @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除" class="pb-icon icon-delete"></i>
                    </template>
                </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total"
                    style="float:right;">
                </el-pagination>
            </el-col>
        </div>
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" :custom-class="dialogTitleColor" @close="editFormVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                    <el-form-item label="角色名" prop="name">
                        <el-input v-model="editForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item  label="描述">
                        <el-input v-model="editForm.remark" auto-complete="off"></el-input>
                    </el-form-item>

                    <!-- <el-form-item label="id">
                        <el-input-number v-model="editForm.id" :min="0" :max="200"></el-input-number>
                    </el-form-item> -->

                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button :type="buttonColor" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>
        <!--权限树编辑界面-->
        <el-dialog title="权限树编辑" v-show="editexentble" :custom-class="dialogTitleColor" @close="editexentble = false">
            <div slot="footer" style="text-align: left; ">
                <el-tree :data="exentform" @check-change="handleCheckChange" :props="defaultProps" show-checkbox
                    node-key="menuId" ref="tree" :expand-on-click-node="false" default-expand-all	 >
                    <!-- <span class="custom-tree-node" slot-scope="{ node, exentform }">
                      <span>{{ node.name }}</span> -->
                </el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editexentble = false">取消</el-button>
                <el-button :type="buttonColor" @click.native="exentSubmit(userid)" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-show="addFormVisible" :custom-class="dialogTitleColor" @close="addFormVisible = false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                    <el-form-item label="角色名" prop="name">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item  label="描述"  >
                        <el-input v-model="addForm.remark" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: right;">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import {
        query_user,
        query_userpost,
        query_userput,
        query_userdelete,
        query_userpermission,
        authorize
    } from '../../api/api';

    export default {
        data() {
            return {
                selfId:'',
                userid: '',
                defaultProps: {
                    children: 'children',
                    label: 'name'

                },

                filters: {
                    name: ''
                },
                num: [],
                users: [],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [], //列表选中列
                exentform: [],
                editexentble: false, //权限树编辑页面是否显示
                editFormVisible: false, //编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [{
                        required: true,
                        message: '请输入名字',
                        trigger: 'blur'
                    },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }]
                },
                //编辑界面数据
                editForm: {
                    id: 0,
                    name: '',
                    remark: '',

                },

                addFormVisible: false, //新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [{
                        required: true,
                        message: '请输入角色名',
                        trigger: 'blur'
                    }, { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                    remark: [{
                        required: true,
                        message: '请输入描述内容',
                        trigger: 'blur'
                    }]
                },
                //新增界面数据
                addForm: {
                    name: '',
                    remark: '',

                }

            }
        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            indexMethod(index) {
                let num = (this.page - 1) * 10 + index + 1;
                return num;
            },
            handleCheckChange(data, checked, indeterminate) {
                data.checked = checked
            },
            //性别显示转换
            formatSex: function (row, column) {
                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            //获取用户列表
            getUsers() {
                if(this.menubt.indexOf('/user_role/query_user')==-1){  this.$message({
                            message: '您没有查询角色列表的权限',
                            type: 'warning'
                        });
                return false;
               }
                let para = {
                    pageNo: this.page,
                    pageSize: 10,
                    name:this.filters.name
                };
                this.listLoading = true;
                //NProgress.start();
                query_user(para).then((res) => {
                    console.log(res)
                     this.begCode(res.code,res.message);
                    this.total = res.data.totalCount;
                    // console.log(res);
                    this.users = res.data.list;
                    this.listLoading = false;
                    this.page=res.data.pageNo;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该角色吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        id: row.id
                    };
                    query_userdelete(para).then((res) => {
                        this.begCode(res.code,res.message);
                            this.listLoading = false;
                        if (res.code == 0) {

                            //NProgress.done();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });

                            this.getUsers();

                        }
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            exentEdit: function (index, row) {
                this.editexentble = true;
                this.userid = row.id;
                let para = {
                    roleId: row.id
                };
                // this.listLoading = true;
                //NProgress.start();
                query_userpermission(para).then((res) => {
                     this.begCode(res.code,res.message);
                    // this.total = res.data.total;
                    // console.log(res);
                    this.exentform = res.data;
                    this.listLoading = false;
                    var num = [];
                    console.log(this.exentform)
                    for (let i in this.exentform) {

                        for (let j in this.exentform[i].children) {
                            this.exentform[i].children[j].children = [];
                            for (let k in this.exentform[i].children[j].actionList) {
                                
                                this.exentform[i].children[j].children.push({
                                    menuId: this.exentform[i].children[j].actionList[k].actionId,
                                    name: this.exentform[i].children[j].actionList[k].actionName,
                                    checked: this.exentform[i].children[j].actionList[k].checked
                                })
                                if (this.exentform[i].children[j].children[k].checked) {
                                    num.push(this.exentform[i].children[j].children[k].menuId);
                                    
                                }
                            }
                            if(!this.exentform[i].children[j].actionList){
                               
                            if (this.exentform[i].children[j].checked) {
                                // console.log(this.exentform[i].children[j].menuId)
                                num.push(this.exentform[i].children[j].menuId);

                            } 
                            }
                        }

                    }
                    console.log(num)
                    this.$refs.tree.setCheckedKeys(num)
                    //NProgress.done();
                });
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    name: '',
                    sex: -1,
                    age: 0,
                    birth: '',
                    addr: ''
                };
            },
            //编辑
            exentSubmit(e) {
                if (e) {
                    this.num = [];
                    //NProgress.start();
                    console.log(this.exentform)
                    for (let i in this.exentform) {
                        var tum = "";
                        var index = 0;
                        
                        for (let j in this.exentform[i].children) {
                            console.log(this.exentform[i].children[j].name+':'+this.exentform[i].children[j].checked)
                                var tum;
                                console.log(this.exentform[i].children[j])
                                if(this.exentform[i].children[j].children.length>0){
                                    let indexclidr=0;
                                    for (let k in this.exentform[i].children[j].children) {
                                    if (this.exentform[i].children[j].children[k].checked) {
                                        
                                        index++;
                                        indexclidr++;
                                        if(indexclidr==1){
                                            tum = {
                                        "menuId": this.exentform[i].children[j].menuId,
                                        "actionId": 0
                                        }
                                        this.num.push(tum);
                                        }
                                     
                                        tum = {
                                            "menuId": this.exentform[i].children[j].menuId,
                                            "actionId": this.exentform[i].children[j].children[k].menuId
                                        }
                                        this.num.push(tum);

                                        console.log(tum)
                                    }
                                }
                                }else{
                                    console.log(this.exentform[i].children[j].checked)
                                    if(this.exentform[i].children[j].checked){
                                        index++;
                                        tum = {
                                        "menuId": this.exentform[i].children[j].menuId,
                                        "actionId": 0
                                        }
                                        this.num.push(tum);
                                    }
                                }
                              

                        }


                        if (index > 0) {
                            console.log(this.exentform[i].menuId)
                            tum = {
                                "menuId": this.exentform[i].menuId,
                                "actionId": 0
                            }
                            this.num.push(tum);
                            console.log(this.num)
                        } else {

                            console.log(tum)
                        }
                    }
                    // alert(JSON.stringify(valid))
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {

                        let para = {
                            roleId: e,
                            permList: this.num
                        };
                        authorize(para).then((res) => {
                             this.begCode(res.code,res.message);
                            if (res.code == 0) {

                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getUsers();
                                this.editexentble = false;

                            } else {
                                this.$message({
                                    message: res.message,
                                    type: 'warning'
                                });
                            }
                        });
                    });
                }
            },
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(
                                new Date(para.birth), 'yyyy-MM-dd');
                            query_userput(para).then((res) => {
                                 this.begCode(res.code,res.message);
                                if (res.code == 0) {

                                    this.editLoading = false;
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();

                                } else {
                                    this.$message({
                                        message: res.message,
                                        type: 'warning'
                                    });
                                }
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(
                                new Date(para.birth), 'yyyy-MM-dd');
                            query_userpost(para).then((res) => {
                                 this.begCode(res.code,res.message);
                                if (res.code == 0) {
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['addForm'].resetFields();
                                    this.addFormVisible = false;
                                    this.getUsers();
                                } else {
                                    this.$message({
                                        message: res.message,
                                        type: 'warning'
                                    });
                                }
                                this.addLoading = false;
                                //NProgress.done();

                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        ids: ids
                    };
                    batchRemoveUser(para).then((res) => {
                         this.begCode(res.code,res.message);
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            
            this.menubt=localStorage.getItem('menubt');
            this.getUsers();
            this.selfId = JSON.parse(sessionStorage.getItem('user')).userId
        }
    }
</script>

<style scoped>

</style>